package com.hengfoxwolf.jetpackdemo
import androidx.lifecycle.DefaultLifecycleObserver
import androidx.lifecycle.LifecycleOwner
import kotlin.properties.ReadWriteProperty
import kotlin.reflect.KProperty

/*
* 自动回收对象
* */
inline fun <reified T : Any> LifecycleOwner.autoClean(noinline objectFactory: () -> T): ReadWriteProperty<LifecycleOwner, T> =
    object : ReadWriteProperty<LifecycleOwner, T> {
        private var objects: T? = null

        init {
            lifecycle.addObserver(object : DefaultLifecycleObserver {
                override fun onDestroy(owner: LifecycleOwner) {
                    super.onDestroy(owner)
                    objects = null
                    lifecycle.removeObserver(this)
                }
            })
        }

        override fun getValue(thisRef: LifecycleOwner, property: KProperty<*>): T {
            objects?.let { return it }
            objects = objectFactory()
            return objects!!
        }

        override fun setValue(thisRef: LifecycleOwner, property: KProperty<*>, value: T) {
            objects = value
        }
    }

/*
* 自动回收对象
* */
inline fun <reified T : Any> LifecycleOwner.autoClean(obj: T): ReadWriteProperty<LifecycleOwner, T> =
    autoClean { obj }
